package com.jy.appmarket.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jy.app.market.idata.data.Login;
import com.jy.appmarket.AppMarketApplication;
import com.jy.appmarket.R;
import com.jy.appmarket.dialog.WaitDialog;
import com.jy.appmarket.network.engine.BaseNetEngine;
import com.jy.appmarket.network.engine.CheckVerifyCodeNetEngine;
import com.jy.appmarket.network.engine.GetVerifyCodeNetEngine;
import com.jy.appmarket.network.engine.SetPasswdNetEngine;
import com.jy.appmarket.network.resultdata.CheckVerifyCodeResult;
import com.jy.appmarket.network.resultdata.GetVerifyCodeResult;
import com.jy.appmarket.network.resultdata.SetPasswdResult;
import com.jy.appmarket.network.task.NetTask;
import com.jy.appmarket.utils.CryptoUtil;
import com.jy.appmarket.utils.LoginUtil;
import com.jy.appmarket.utils.StringUtil;
import com.umeng.analytics.MobclickAgent;

/**
 * @author :    jiangwei
 * @time :      2018/05/22
 * @desc :      注册新页面
 * @virsion :   1.0.0
 */
public class RegisterActivity extends FragmentActivity implements View.OnClickListener, NetTask.NetTaskListener {
    public static final int TIMER_EXECUTE = 0x01;
    private ImageView ivBack;
    private TextView tvLogin;
    private EditText etPhone;
    private EditText etCode;
    private TextView tvSendCode;
    private EditText etPassword;
    private CheckBox cbAgreement;
    private TextView tvSign;

    private WaitDialog mWaitDialog;
    private String mPhoneNum;
    private String mVerifyCode;
    private String mPasswd;
    private NetTask mNetTask;
    private NetTask mNetTask2;
    private NetTask mNetTask3;
    private NetTask mNetTas4;

    private boolean mIsNeedGetVerifyCode;
    private int mVerifyCodeInterval;

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case TIMER_EXECUTE:
                    refreshUI();
                    break;

                default:
                    break;
            }
        }

    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView();
    }

    private void initView() {
        ivBack = findViewById(R.id.iv_register_back);
        ivBack.setOnClickListener(this);
        tvLogin = findViewById(R.id.tv_register_login);
        tvLogin.setOnClickListener(this);
        etPhone = findViewById(R.id.et_register_phone);
        etCode = findViewById(R.id.et_register_code);
        tvSendCode = findViewById(R.id.tv_register_send_code);
        tvSendCode.setOnClickListener(this);
        etPassword = findViewById(R.id.et_register_password);
        cbAgreement = findViewById(R.id.cb_register_agreement);
        tvSign = findViewById(R.id.tv_register_sign);
        tvSign.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //返回
            case R.id.iv_register_back:
                finish();
                break;
            //登录
            case R.id.tv_register_login:
                startActivity(new Intent(RegisterActivity.this, UserLoginActivity.class));
                break;
            //发送验证码
            case R.id.tv_register_send_code:
                getVerifyCode();
                break;
            //注册
            case R.id.tv_register_sign:
                register();
                break;
            default:
                break;
        }
    }

    private void getVerifyCode() {
        mPhoneNum = etPhone.getText().toString().trim();
        mVerifyCodeInterval = 60;
        tvSendCode.setEnabled(false);
//        mSendVerifyCodeBtn.setBackgroundResource(R.drawable.download_button_gray);
        tvSendCode.setText(mVerifyCodeInterval + "秒后重发");
        Message msg = mHandler.obtainMessage();
        msg.what = TIMER_EXECUTE;
        mHandler.sendMessageDelayed(msg, 1000);

        GetVerifyCodeNetEngine engine = new GetVerifyCodeNetEngine(mPhoneNum, "register");
        mNetTask = new NetTask(this, engine, 0);
        mNetTask.setListener(this);
        new Thread(mNetTask).start();
    }

    private void checkVerifyCode() {
        showWaitDialog();
        CheckVerifyCodeNetEngine engine = new CheckVerifyCodeNetEngine(mPhoneNum, "register", mVerifyCode);
        mNetTask2 = new NetTask(this, engine, 1);
        mNetTask2.setListener(this);
        new Thread(mNetTask2).start();
    }

    public void refreshUI() {
        if (mVerifyCodeInterval > 0) {
            mVerifyCodeInterval--;
            tvSendCode.setText(mVerifyCodeInterval + "秒后重发");
            Message msg = mHandler.obtainMessage();
            msg.what = TIMER_EXECUTE;
            mHandler.sendMessageDelayed(msg, 1000);
        } else {
//            mSendVerifyCodeBtn.setBackgroundResource(R.drawable.download_button_blue);
            tvSendCode.setEnabled(true);
            tvSendCode.setText(R.string.send_verify_code);
        }
    }

    private void bindPhone() {
        showWaitDialog();
        SetPasswdNetEngine engine = new SetPasswdNetEngine(mPhoneNum, CryptoUtil.md5(mPasswd), "register", mVerifyCode);
        mNetTas4 = new NetTask(this, engine, 4);
        mNetTas4.setListener(this);
        new Thread(mNetTas4).start();
    }

    private void register() {
        mPhoneNum = etPhone.getText().toString().trim();
        mVerifyCode = etCode.getText().toString().trim();
        mPasswd = etPassword.getText().toString();

        if (TextUtils.isEmpty(mPhoneNum)) {
            Toast.makeText(RegisterActivity.this, R.string.please_input_username,
                    Toast.LENGTH_SHORT).show();
            return;
        }
        if (mPhoneNum.length() != 11) {
            Toast.makeText(RegisterActivity.this, R.string.username_format_error,
                    Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(mVerifyCode)) {
            Toast.makeText(this, R.string.please_input_verify_code,
                    Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(mPasswd)) {
            Toast.makeText(this, R.string.please_input_password,
                    Toast.LENGTH_SHORT).show();
            return;
        }

        if (StringUtil.hasSpaceChar(mPasswd)) {
            Toast.makeText(this, R.string.password_not_has_space,
                    Toast.LENGTH_SHORT).show();
            return;
        }

        if (mPasswd.length() < 6) {
            Toast.makeText(this, R.string.password_format_error,
                    Toast.LENGTH_SHORT).show();
            return;
        }

        checkVerifyCode();
    }

    @Override
    public void onTaskRunSuccessful(int tag, BaseNetEngine engine) {
        dismissWaitDialog();
        if (tag == 0) {
            GetVerifyCodeResult resultData = (GetVerifyCodeResult) engine.getResultData();
            if (!resultData.isOK()) {
                String message = resultData.getMessage();
                if (!TextUtils.isEmpty(message)) {
                    Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, R.string.get_verify_code_error, Toast.LENGTH_SHORT).show();
                }
                mVerifyCodeInterval = 0;
            } else {
                Toast.makeText(this, R.string.get_verify_code_success, Toast.LENGTH_SHORT).show();
            }
        } else if (tag == 1) {
            CheckVerifyCodeResult resultData = (CheckVerifyCodeResult) engine.getResultData();
            if (!resultData.isOK()) {
                String message = resultData.getMessage();
                if (!TextUtils.isEmpty(message)) {
                    Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, R.string.check_verify_code_error, Toast.LENGTH_SHORT).show();
                }
            } else {
                bindPhone();
            }
        } else {
            SetPasswdResult resultData = (SetPasswdResult) engine.getResultData();
            if (!resultData.isOK()) {
                if (resultData.getStatus() == 461) {
                    //如果返回461为验证码已经失效，客户端需要关闭设置密码页面，用户需要从新获取验证码
//                    backToGetVerifyCode();
                } else {
                    String message = resultData.getMessage();
                    if (!TextUtils.isEmpty(message)) {
                        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, R.string.set_passwd_error, Toast.LENGTH_SHORT).show();
                    }
                }
            } else {
                // 如果是注册，设置为登录状态
                Login login = resultData.getLogin();
                AppMarketApplication.setLogin(login);
                LoginUtil.saveLogin(this, login);

                Intent intent = new Intent(this, ModifyUserInfoActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString(ModifyUserInfoActivity.EXTRA_NAME, "完善个人资料（3/3）");
                bundle.putBoolean(ModifyUserInfoActivity.EXTRA_IS_SHOW_MENU, true);
                intent.putExtras(bundle);
                startActivity(intent);
                finish();
            }
        }

    }

    @Override
    public void onTaskRunError(int tag) {
        dismissWaitDialog();
        Toast.makeText(RegisterActivity.this, R.string.network_error, Toast.LENGTH_SHORT).show();
        return;
    }

    @Override
    public void onTaskRunCanceled(int tag) {
        dismissWaitDialog();
    }

    @Override
    public void onDestroy() {
        if (mNetTask != null) {
            mNetTask.cancel();
            mNetTask.setListener(null);
            mNetTask = null;
        }
        if (mNetTask2 != null) {
            mNetTask2.cancel();
            mNetTask2.setListener(null);
            mNetTask2 = null;
        }
        if (mNetTask3 != null) {
            mNetTask3.cancel();
            mNetTask3.setListener(null);
            mNetTask3 = null;
        }
        if (mNetTas4 != null) {
            mNetTas4.cancel();
            mNetTas4.setListener(null);
            mNetTas4 = null;
        }
        dismissWaitDialog();
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    private void showWaitDialog() {
        if (mWaitDialog == null) {
            mWaitDialog = new WaitDialog(this);
            mWaitDialog.setCanceledOnTouchOutside(false);
            mWaitDialog.setCancelable(false);
        }
        if (mWaitDialog.isShowing()) {
            return;
        }
        mWaitDialog.showTitle("请稍候...").show();
    }

    private void dismissWaitDialog() {
        if (mWaitDialog != null) {
            mWaitDialog.dismiss();
        }
    }
}
